import tkinter as tk
from tkinter import ttk
from view.commonmodels import *
from tkinter import filedialog
import os


class FFChooser(tk.Frame):
    def __init__(self, root, mood: str = 'file', command=None, **kwarg):
        super(FFChooser, self).__init__(root, **kwarg)
        self.mood = mood
        self.fpath = None
        self.fname = None
        self.addr = None
        # self.vfname = tk.StringVar(self)
        # self.entry = tk.Entry(self, textvariable=self.vfname, validatecommand=lambda :False)
        self.vfname = RonlyEntry(self, width=30)
        self.extracmd = command

        if self.mood == 'file':
            self.checkbutton = tk.Button(self, text="选择文件", width=10, command=self.choose)
            self.vfname.set("请选择文件...")
        elif self.mood == 'folder':
            self.checkbutton = tk.Button(self, text="选择文件夹", width=10, command=self.choose)
            self.vfname.set("请选择文件夹...")

        if self.mood == 'file':
            tk.Label(self, text="文件名:", width=7).grid(row=0, column=0)
        if self.mood == 'folder':
            tk.Label(self, text="文件夹:", width=7).grid(row=0, column=0)

        self.vfname.grid(row=0, column=1)
        self.checkbutton.grid(row=0, column=2)

    def choose(self):
        state = False
        if self.mood == "folder":
            fpath = tk.filedialog.askdirectory()
        elif self.mood == "file":
            fpath = tk.filedialog.askopenfilename()
        self.focus_force()
        if self.fpath != '':
            state = True
            self.fpath = fpath
            print(f">>{self.fpath}")
            print(f">>文件地址有效")
            self.fname = os.path.basename(self.fpath)
            self.vfname.set(self.fname)
        if callable(self.extracmd):
            self.extracmd()
        return state
        # print(f"文件路径为：{self.fpath}")
        # print(f"文件名为  ：{self.fname}")

    def selected(self):
        return (self.fname, self.fpath)


class FileChooser(tk.Frame):
    def __init__(self, root, multiple=False, initialdir=os.getcwd(), command=None, defaultextension='.json',
                 filetypes=[('All Files', '*'), ('json文件', '.json')], **kwarg):
        super(FileChooser, self).__init__(root, **kwarg)
        self.mood = multiple
        self.files = {}
        self.addr = None
        self.filenames = []
        self.filetypes = filetypes
        self.initialdir = initialdir
        self.defaultextension = defaultextension
        self.extracmd = command
        self.vfname = RonlyEntry(self, width=20)
        self.checkbutton = ttk.Button(self, text="选择图片", width=10, command=self.choose)
        self.vfname.set("请选择图片...")
        self.vfname.grid(row=0, column=0)
        self.checkbutton.grid(row=0, column=1)

    def choose(self):
        if self.mood:
            state = self._choosefiles()
        else:
            state = self._chooseonefile()
        if state and callable(self.extracmd):
            self.extracmd()

        return state
    def reset_initialdir(self, initialdir):
        self.initialdir = initialdir
    def _chooseonefile(self):
        state = False
        fpath = tk.filedialog.askopenfilename(title='请选择一个文件', initialdir=self.initialdir,
                                              filetypes=self.filetypes, defaultextension=self.defaultextension)
        self.focus_force()
        if fpath != '':
            state = True
            self.files = {}
            print(f"文件地址有效:")
            print(f">> {fpath}\n")
            fname = os.path.basename(fpath)
            self.files[fname] = fpath
            self.vfname.set(fname)
            self.filenames = [fname,]
            print(self.filenames)

        return state

    def _choosefiles(self):
        state = False
        fpath = tk.filedialog.askopenfilenames(title='请选择一个文件', initialdir=self.initialdir,
                                               filetypes=self.filetypes, defaultextension=self.defaultextension)
        self.focus_force()
        if fpath != '':
            state = True
            self.files = {}
            filenamelist = []
            print(f"文件地址有效:")
            for path in fpath:
                print(f">> {path}")
                filenamelist.append(os.path.basename(path))
                self.files[filenamelist[-1]] = path

            print('\n')
            fnames = str(filenamelist).replace('\'', '').replace('[', '').replace(']', '')
            self.vfname.set(str(fnames))
            self.filenames = filenamelist[:]

        if callable(self.extracmd):
            self.extracmd()
        return state

    def selected(self):
        return self.files

    def resetcommand(self, command):
        if callable(command):
            self.checkbutton.configure(command=command)


class FolderChooser(tk.Frame):
    def __init__(self, root, initialdir=os.getcwd(), command=None, **kwarg):
        super(FolderChooser, self).__init__(root, **kwarg)
        self.fpath = None
        self.fname = None
        self.initialdir = initialdir
        self.extracmd = command
        self.vfname = RonlyEntry(self, width=30)
        self.checkbutton = tk.Button(self, text="选择文件夹", width=10, command=self.choose)
        self.vfname.set("请选择文件夹...")
        tk.Label(self, text="文件夹:", width=7).grid(row=0, column=0)
        self.vfname.grid(row=0, column=1)
        self.checkbutton.grid(row=0, column=2)

    def choose(self):
        state = False
        fpath = tk.filedialog.askdirectory(title='请选择一个文件', initialdir=self.initialdir)
        self.focus_force()
        if self.fpath != '':
            state = True
            self.fpath = fpath
            print("文件夹地址有效:")
            print(f">> {fpath}")
            self.fname = os.path.basename(self.fpath)
            self.vfname.set(self.fname)
        if callable(self.extracmd):
            self.extracmd()
        return state

    def selected(self):
        return (self.fname, self.fpath)


class FileSaver:
    def __init__(self, root, title="请选择文件保存位置", initaldir=os.getcwd(), filetypes=[('All Files', '*'), ('json文件', '.json')],
                 initialfile='*'):
        self.title = title
        self.initaldir = initaldir
        self.filetypes = filetypes
        self.initialfile = initialfile
        self.root = root

    def save(self):
        savepath = filedialog.asksaveasfilename(title=self.title, initialdir=self.initaldir, filetypes=self.filetypes,
                                     initialfile=self.initialfile)
        self.root.focus_force()
        filename = os.path.basename(savepath)
        return (filename, savepath)

    def setinitialfile(self, initialfile):
        self.initialfile = initialfile